package com.brick.controller;

import com.brick.entity.Result;
import com.brick.entity.ShoppingCart;
import com.brick.service.ShoppingCarService;
import com.brick.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import static com.brick.util.Util.util;

@RequestMapping("/api/shoppingCartServlet")
@RestController
public class ShoppingCarController {
    @Autowired
    ShoppingCarService shoppingCarService;


    @RequestMapping("/getShoppingCart")
    public Result<List<ShoppingCart>> getShoppingCart(@RequestBody ShoppingCart shoppingCart, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return ResultUtil.error(0,bindingResult.getFieldError().getDefaultMessage());
        }
        return ResultUtil.success(shoppingCarService.selectAll(shoppingCart));
    }

    @Transactional
    @RequestMapping("/addShoppingCart")
    public Result addShoppingCart(@RequestBody ShoppingCart shoppingCart, BindingResult bindingResult){
        shoppingCart.setId(util.getUUID());
        shoppingCart.setDateline(util.getDateNow());
        shoppingCart.setLoseEfficacy(1);
        shoppingCart.setState(1);
        try{
            return ResultUtil.success(shoppingCarService.insert(shoppingCart));
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(0, bindingResult.getFieldError().getDefaultMessage());
        }
    }

    @RequestMapping("/updateShoppingCart")
    public Result updateShoppingCart(@RequestBody ShoppingCart user, BindingResult bindingResult){
        int i = 1;
        if (bindingResult.hasErrors()){
            return ResultUtil.error(0,bindingResult.getFieldError().getDefaultMessage());
        }
        return ResultUtil.success(shoppingCarService.update(user));
    }
}
